import { FC, useEffect, useMemo, useReducer, useState } from "react";
import { FormItemChildProps } from "../../types/comp";
import CardWrap from "./CardWrap";
import request from "../../utils/request";
import { BusinessItemListInfo, ElementItem } from "../../types/business";
import CheckImgList from "../CheckImgList";
import {
  clone,
  cloneDeep,
  filter,
  find,
  findIndex,
  forEach,
  get,
  isArray,
  map,
  pick,
  set,
} from "lodash";
import Dialog from "../Dialog";
import { Button, Cascader, Modal } from "antd";
import dialog from "../Dialog";
import ElementSelector from "./ElementSeletor";
import ImageListUpload from "./ImageListUpload";
const ElementSelectorCtrl: FC<FormItemChildProps> = ({ value, onChange }) => {
  const [modalFlag, showModal] = useReducer((v) => v + 1, 0);
  const [innerValue, setInnerValue] = useState<string[]>([]);
  const [list, setList] = useState<ElementItem[]>([]);

  useEffect(() => {
    void (async () => {
      const list = await request.get("/pattern/info/element/list");
      forEach(value, (source) => {
        forEach(list, (group) => {
          forEach(group.sub_tag_list, (item) => {
            if (item.id === source.id) {
              item.score = source.score;
              item.threshold = source.threshold;
            }
          });
        });
      });
      setList(list);
      setInnerValue(map(value, (item) => item?.id));
    })();
  }, []);
  useEffect(() => {
    const result: any[] = [];
    let item: ElementItem;
    forEach(innerValue, (source) => {
      forEach(list, (group) => {
        forEach(group.sub_tag_list, (innerItem) => {
          if (innerItem.id === source) {
            item = clone(innerItem);
          }
        });
      });
      if (!item) return;
      result.push({
        id: item.id,
        threshold: item.threshold,
        score: item.score,
      });
    });
    onChange?.(result);
  }, [innerValue, list]);
  const previewList = useMemo(() => {
    const idList = map(value, (item) => get(item, "id"));
    const result = [];
    forEach(list, (group) => {
      if (idList.length === result.length) return result;
      forEach(get(group, "sub_tag_list", []), (item) => {
        if (idList.includes(item?.id)) {
          result.push({
            id: item?.id,
            url: item?.url,
            title: item?.title,
          });
        }
      });
    });
    return result;
  }, [value, list]);

  return (
    <>
      <ImageListUpload
        value={previewList}
        btnNode={
          <Button type="primary" onClick={showModal} size="small">
            元素选取
          </Button>
        }
        sourceAtr="url"
        labelAtr="title"
      />
      <ElementSelector
        list={list}
        setList={setList}
        flag={modalFlag}
        value={innerValue}
        onChange={setInnerValue}
      />
    </>
  );
};
export default ElementSelectorCtrl;
